//
//  AnnouncerMoreViewController.m
//  MountEverestFM
//
//  Created by ChenNing on 15/11/7.
//  Copyright © 2015年 chenn. All rights reserved.
//

#import "AnnouncerMoreViewController.h"
#import "AnnouncerMoreTableViewCell.h"
#import "TPIViewController.h"
#import "Player.h"
#import "MusicModel.h"
#import "PlayerModel.h"
#import "CategoryViewController.h"

@interface AnnouncerMoreViewController ()<UITableViewDataSource,UITableViewDelegate,CategoryViewControllerDelegate>

@property(nonatomic,strong)NSArray *dataHotArray;
@property(nonatomic,strong)NSArray *dataNewArray;

@property(nonatomic,strong)UITableView *annTableView;

// 全部分类
@property(nonatomic,assign)BOOL isClick;
@property(nonatomic,strong)UIButton *naviButton;
@property(nonatomic,strong)UIImageView *naviImageView;
@property(nonatomic,strong)UIView *showAllView;
@property(nonatomic,strong)CategoryViewController *cateVC;

// 最热,最新
@property(nonatomic,strong)UISegmentedControl *segControl;
@property(nonatomic,assign)NSInteger selectIndex;
@property(nonatomic,assign)CGFloat hotOffSet;
@property(nonatomic,assign)CGFloat newOffSet;

// 试听
@property(nonatomic,assign)NSInteger indexRow;
@property(nonatomic,assign)BOOL isPlaying;

//页码
@property(nonatomic,assign)NSInteger hotPage;
@property(nonatomic,assign)BOOL hotIsRefresh;

@property(nonatomic,assign)NSInteger newPage;
@property(nonatomic,assign)BOOL newIsRefresh;

@end

@implementation AnnouncerMoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initAnnMoreTableView];
    
    // 显示全部分类button
    CGRect naviBtnRect = [self.titleStr boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} context:nil];
    
    self.naviButton = [UIButton buttonWithType:UIButtonTypeCustom];//button的类型
    self.naviButton.frame = CGRectMake(FM_Screen_Width/2-(naviBtnRect.size.width+50)/2, 35,naviBtnRect.size.width+50, 20);//button的frame

    //    在UIButton中有三个对EdgeInsets的设置：ContentEdgeInsets、titleEdgeInsets、imageEdgeInsets
    [self.naviButton setImage:[UIImage imageNamed:@"navidrop_arrow_down_n@2x.png"] forState:UIControlStateNormal];//给button添加image
    self.naviButton.imageEdgeInsets = UIEdgeInsetsMake(0,naviBtnRect.size.width+20,0,0);//设置image在button上的位置
    [self.naviButton setTitle:self.titleStr forState:UIControlStateNormal];//设置button的title
    self.naviButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];//title字体大小
    self.naviButton.titleLabel.textAlignment = NSTextAlignmentCenter;//设置title的字体居中
    
    [self.naviButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.naviButton setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    self.naviButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20);//设置title在button上的位置（上top，左left，下bottom，右right）
    [self.naviButton addTarget:self action:@selector(showAllAnnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.naviButton addTarget:self action:@selector(touchDownAction:) forControlEvents:UIControlEventTouchDown];
    [self.navigationController.view addSubview:_naviButton];
}

- (void)showAllAnnAction:(UIButton *)sender
{
    _isClick = !_isClick;
    if(_isClick){
        // 更改button的背景图
        [self.naviButton setImage:[UIImage imageNamed:@"navidrop_arrow_up_n@2x.png"] forState:UIControlStateNormal];
        // 显示列表页
        if (self.cateVC==nil) {
            self.cateVC = [[CategoryViewController alloc] init];
            self.cateVC.selectedTitleStr = self.titleStr;
            self.cateVC.delegate = self;
            [self.view addSubview:self.cateVC.view];
            [self addChildViewController:self.cateVC];
        }else{
            self.cateVC.view.hidden = NO;
        }
    }else{
        [self.naviButton setImage:[UIImage imageNamed:@"navidrop_arrow_down_n@2x.png"] forState:UIControlStateNormal];
        // 隐藏列表页
        self.cateVC.view.hidden = YES;
    }
}

#warning 更改橘黄色箭头
- (void)touchDownAction:(UIButton *)sender
{
    // 更改橘黄色箭头
    
}

/**
 *  初始化mlTableView
 */
- (void)initAnnMoreTableView
{
    self.hotPage = 1;
    self.newPage = 1;
    self.dataHotArray = [NSMutableArray array];
    self.dataNewArray = [NSMutableArray array];
    self.annTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,64, FM_Screen_Width,FM_Screen_Height-64-48) style:UITableViewStylePlain];
    self.annTableView.dataSource = self;
    self.annTableView.delegate = self;
    self.annTableView.backgroundColor = UIColorFromRGB(0xe7e7e7);
    [self.view addSubview:_annTableView];
    
    [self.annTableView registerClass:[AnnouncerMoreTableViewCell class] forCellReuseIdentifier:@"annMoreCell"];
    [self setupRefresh];
}

// UITableViewDataSource 协议方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.selectIndex == 0) {
        // 最热
        return self.dataHotArray.count;
    }
    else
    {
        // 最新
        return self.dataNewArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return FM_Screen_Pts_Height*60;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FM_Screen_Width, FM_Screen_Pts_Height*50)];
    view.backgroundColor = UIColorFromRGB(0xe7e7e7);
    NSArray *segArr = [NSArray arrayWithObjects:@"最热",@"最新", nil];
    self.segControl = [[UISegmentedControl alloc] initWithItems:segArr];
    self.segControl.frame = CGRectMake(FM_Screen_Pts_Width*10,FM_Screen_Pts_Height*10,  FM_Screen_Width-FM_Screen_Pts_Width*20, FM_Screen_Pts_Height*40);
    self.segControl.tintColor = [UIColor orangeColor];
    self.segControl.selectedSegmentIndex = self.selectIndex;
    [self.segControl addTarget:self action:@selector(selectSegAction:) forControlEvents:UIControlEventValueChanged];
    [view addSubview:_segControl];
    return view;
}

- (void)selectSegAction:(UISegmentedControl *)sender
{
    if (sender.selectedSegmentIndex == 0) {
        // 最热
        self.selectIndex = 0;
        if (self.dataHotArray.count == 0) {
            [self setupRefresh];
        }else{
          self.annTableView.contentOffset =  CGPointMake(0, self.hotOffSet);
            [self.annTableView reloadData];
        }
    }
    else
    {
        // 最新
        self.selectIndex = 1;
        if (self.dataNewArray.count == 0) {
            [self setupRefresh];
        }else{
            self.annTableView.contentOffset = CGPointMake(0, self.newOffSet);
            [self.annTableView reloadData];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return FM_Screen_Pts_Width*150;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnnouncerMoreTableViewCell *annMoreCell = [tableView dequeueReusableCellWithIdentifier:@"annMoreCell"];
    if (self.selectIndex == 0) {
        // 最热
        annMoreCell.annMoreDic = [self.dataHotArray objectAtIndex:indexPath.row];
    }
    else
    {
        // 最新
        annMoreCell.annMoreDic = [self.dataNewArray objectAtIndex:indexPath.row];
    }
    annMoreCell.tryListenButton.tag = indexPath.row + 10500;
    [annMoreCell.tryListenButton addTarget:self action:@selector(tryListenAction:) forControlEvents:UIControlEventTouchUpInside];
    return annMoreCell;
}

- (void)tryListenAction:(UIButton *)sender
{
    // 还原旧图标
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.indexRow inSection:0];
    AnnouncerMoreTableViewCell *oldMoreCell = [self.annTableView cellForRowAtIndexPath:indexPath];
    [oldMoreCell.tryListenButton setBackgroundImage:[UIImage imageNamed:@"sound_playbtn@2x.png"] forState:UIControlStateNormal];
    oldMoreCell.contentView.backgroundColor = [UIColor whiteColor];
    
    AnnouncerMoreTableViewCell *newMoreCell = [self.annTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:sender.tag-10500 inSection:0]];
    if(!self.isPlaying){
        // 试听,更还播放图标
        [newMoreCell.tryListenButton setBackgroundImage:[UIImage imageNamed:@"find_hotuser_pause@2x.png"] forState:UIControlStateNormal];
        self.indexRow = sender.tag-10500;
        // 播放试听
        if (self.selectIndex == 0) {
            NSString *uid = [[self.dataHotArray objectAtIndex:indexPath.row] objectForKey:@"uid"];
            [self playingFMWithUid:uid index:self.indexRow];
        }else{
            NSString *uid = [[self.dataNewArray objectAtIndex:indexPath.row] objectForKey:@"uid"];
            [self playingFMWithUid:uid index:self.indexRow];
        }
    }else{
        // 停止试听,还原图标
        [newMoreCell.tryListenButton setBackgroundImage:[UIImage imageNamed:@"sound_playbtn@2x.png"] forState:UIControlStateNormal];
        self.indexRow = sender.tag-10500;
        // 停止试听
        Player *player = [Player shareInstance];
        [player.audioPlayer pause];
        self.isPlaying = NO;
    }
}

// 播放音频
- (void)playingFMWithUid:(NSString *)uid index:(NSInteger)index
{
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/track/%@/1/30?device=iPhone",uid];
    [NetWorkManager GET:url isCaChe:NO resultData:^(id responseObject) {
        self.isPlaying = YES;
#warning 试听
        Player *player = [Player shareInstance];

//        player.listArr = [responseObject objectForKey:@"list"];
        //处理数据源
        PlayerModel *playerModel = [PlayerModel modelWithDic:responseObject];
        // 专辑序号
        playerModel.index = index;
        // 专辑请求地址
        playerModel.requstUrl = url;
        // 专辑列表
        playerModel.musicArray = [NSArray arrayWithArray:[MusicModel modelWithArr:[responseObject objectForKey:@"list"]]];
        
        // 数据源
        player.playerModel = playerModel;
        // 播放
        [player playFromNet];
    } resultRrror:^(NSError *error) {
        NSLog(@"主播声音信息:error,%@",error);
    }];
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TPIViewController *tpiVC = [[TPIViewController alloc] init];
    if (self.selectIndex == 0) {
        // 最热
        tpiVC.tpiDic = [self.dataHotArray objectAtIndex:indexPath.row];
    }else{
        // 最新
        tpiVC.tpiDic = [self.dataNewArray objectAtIndex:indexPath.row];
    }
    [self.navigationController pushViewController:tpiVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  网络请求
 */
- (void)getHotDataWithUrl
{
    if (!self.hotIsRefresh) {
        // 加载更多
        self.hotPage++;
    }else{
        // 刷新
        self.hotPage=1;
    }
    self.selectIndex = 0;
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_list?category_name=%@&condition=hot&device=iPhone&page=%ld&per_page=20",self.key,self.hotPage];
    [NetWorkManager GET:url isCaChe:NO resultData:^(id responseObject) {
        if (responseObject != nil) {
            if (self.hotPage == 1) {
                self.dataHotArray = [NSMutableArray array];
            }
            NSArray *tempArr = [responseObject objectForKey:@"list"];
            self.dataHotArray = [self.dataHotArray arrayByAddingObjectsFromArray:tempArr];
            [self.annTableView reloadData];
            [self setupEndRefresh];
        }
        // 移除加载更多
        if ([[responseObject objectForKey:@"maxPageId"] integerValue] == self.hotPage) {
            self.annTableView.footer = nil;
        }else{
            // 尾
            self.annTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                if (self.selectIndex == 0) {
                    // 发送最热请求
                    self.hotIsRefresh = NO;
                    self.hotOffSet = 0;
                    [self getHotDataWithUrl];
                }
                else
                {
                    // 发送最新请求
                    self.newIsRefresh = NO;
                    self.newOffSet = 0;
                    [self getNewDataWithUrl];
                }
            }];
        }
    } resultRrror:^(NSError *error) {
        NSLog(@"主播更多:error,%@",error);
    }];
}

- (void)getNewDataWithUrl
{
    if (!self.newIsRefresh) {
        // 加载更多
        self.newPage++;
    }else{
        // 刷新
        self.newPage=1;
    }
    self.selectIndex = 1;
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_list?category_name=%@&condition=new&device=iPhone&page=%ld&per_page=20",self.key,self.newPage];
    [NetWorkManager GET:url isCaChe:NO resultData:^(id responseObject) {
        if (responseObject != nil) {
            if (self.newPage == 1) {
                self.dataNewArray = [NSMutableArray array];
            }
            NSArray *tempArr = [responseObject objectForKey:@"list"];
            self.dataNewArray = [self.dataNewArray arrayByAddingObjectsFromArray:tempArr];
            [self.annTableView reloadData];
            [self setupEndRefresh];
        }
        // 移除加载更多
        if ([[responseObject objectForKey:@"maxPageId"] integerValue] == self.newPage) {
            self.annTableView.footer = nil;
        }else{
            // 尾
            self.annTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                if (self.selectIndex == 0) {
                    // 发送最热请求
                    self.hotIsRefresh = NO;
                    self.hotOffSet = 0;
                    [self getHotDataWithUrl];
                }
                else
                {
                    // 发送最新请求
                    self.newIsRefresh = NO;
                    self.newOffSet = 0;
                    [self getNewDataWithUrl];
                }
            }];
        }
    } resultRrror:^(NSError *error) {
        NSLog(@"主播更多:error,%@",error);
    }];
}

// 设置刷新
- (void)setupRefresh
{
    // 头
    self.annTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (self.selectIndex == 0) {
            // 发送最热请求
            self.hotIsRefresh = YES;
            self.hotOffSet = 0;
            [self getHotDataWithUrl];
        }
        else
        {
            // 发送最新请求
            self.newIsRefresh = YES;
            self.newOffSet = 0;
            [self getNewDataWithUrl];
        }
    }];
    [self.annTableView.header beginRefreshing];
    
    // 尾
    self.annTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.selectIndex == 0) {
            // 发送最热请求
            self.hotIsRefresh = NO;
            self.hotOffSet = 0;
            [self getHotDataWithUrl];
        }
        else
        {
            // 发送最新请求
            self.newIsRefresh = NO;
            self.newOffSet = 0;
            [self getNewDataWithUrl];
        }
    }];
}

// 结束刷新
- (void)setupEndRefresh
{
    [self.annTableView.header endRefreshing];
    [self.annTableView.footer endRefreshing];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.naviButton removeFromSuperview];
    [self.naviImageView removeFromSuperview];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.selectIndex == 0) {
        // 最热
        self.hotOffSet = scrollView.contentOffset.y;
    }
    else
    {
        // 最新
        self.newOffSet = scrollView.contentOffset.y;
    }
}

- (void)anncouncerController:(NSString *)key title:(NSString *)title
{
    self.key = key;
    self.titleStr = title;
    self.cateVC.selectedTitleStr = title;
    CGRect naviBtnRect = [self.titleStr boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16]} context:nil];
    self.naviButton.frame = CGRectMake(FM_Screen_Width/2-(naviBtnRect.size.width+50)/2, 35,naviBtnRect.size.width+50, 20);
    self.naviButton.imageEdgeInsets = UIEdgeInsetsMake(0,naviBtnRect.size.width+20,0,0);
    [self.naviButton setTitle:title forState:UIControlStateNormal];
    self.cateVC.view.hidden = YES;
    self.isClick = !self.isClick;
    [self.naviButton setImage:[UIImage imageNamed:@"navidrop_arrow_down_n@2x.png"] forState:UIControlStateNormal];
    NSInteger segIndex = self.segControl.selectedSegmentIndex;
    if (segIndex == 0) {
        // 发送最热请求
        self.hotOffSet = 0;
        [self getHotDataWithUrl];
    }
    else
    {
        // 发送最新请求
        self.newOffSet = 0;
        [self getNewDataWithUrl];
    }
}

@end
